/*********************************************************************************
Organization 					: 				Georgia Institute of Technology
  
Institute 						:				Cognitive Computing Group(CCL)
 
Authors							: 				Santiago Ontanon, Kinshuk Mishra
 												Neha Sugandh 
 												
Class							:				Condition
 
Function						: 				Provides a class for holding 
												the generic condition class
****************************************************************************/
package planninglanguage.conditions;

import java.io.PrintStream;
import java.io.Serializable;
import java.lang.reflect.Method;

import org.jdom.Element;

import util.XMLWriter;
import base.WargusGameState;

public class Condition implements Serializable{

	public static PrintStream m_logger = null;
	
	public boolean test(WargusGameState a_gameState)
	{
		return true;
	}
	
	public void reset()
	{
	}	
	
	public String toString() {
		return toString(0);
	}

	public String toString(int tabs) {
		String str= new String();
	/*	int i;
		
		for(i=0;i<tabs;i++) str = str + "  ";
		return str + this.getClass().getName() + "()";*/
		return str;
	}
	public void writeXML(XMLWriter w) {
		w.tag("condition type=\""+this.getClass().getSimpleName()+"\"", "");
	}
	public static void writeXML(XMLWriter w, Condition c) {
		if (c == null) {
			w.tag("condition", "");
		} else {
			c.writeXML(w);
		}
	}
	protected static Condition loadConditionFromXML(Element e) {
		return new Condition();
	}
	
	// sadly(?) this ties the class name to the output.. 
	public static Condition loadFromXML(Element e) {
		if (e.getContent().size() == 0	) return null;
		
		String type = e.getAttributeValue("type");
		if (type == null) return null;
		try {
			Method[] methods =
				Class.forName("planninglanguage.conditions." + type).getDeclaredMethods();
			for (Method m : methods) {
				if (m.getName().equals("loadConditionFromXML")) {
					return (Condition) m.invoke(null, new Object[]{e});
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			System.exit(0);
		}
		throw new Error("Condition.loadFromXML: unsupported plan type '" + type + "'");
	}
	
	// test my crazy introspective class loading
	public static void main(String[] args) {
		Element e = new Element("condition").setAttribute("type", "AttackedCondition");
		e.addContent(new Element("unit-id").setText("1"));
		e.addContent(new Element("initial-cycle").setText("99"));
		
		Condition c = Condition.loadFromXML(e);
		AttackedCondition ac = (AttackedCondition) c;
		System.out.println(ac);
	}
}
